<template>
	<section>
		<!--工具条-->
		<el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
			<el-form :inline="true" :model="filters">
				<el-form-item>
					<el-input v-model="filters.keyword" placeholder="关键字"/>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" v-on:click="findCurrent">查询</el-button>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" @click="handleAdd">新增</el-button>
				</el-form-item>
			</el-form>
		</el-col>

		<!--列表-->
		<el-table :data="departments" highlight-current-row v-loading="listLoading" @selection-change="selsChange" style="width: 100%;">
			<el-table-column type="selection" width="55">
			</el-table-column>
			<el-table-column type="index" width="60">
		</el-table-column>
			<el-table-column prop="sn" label="部门编号" width="100" sortable>
			</el-table-column>
			<el-table-column prop="name" label="部门名称" width="200" sortable>
			</el-table-column>
			<el-table-column prop="state" label="部门状态" width="100" sortable>
				<template scope="scope">
					<span style="color: #11b95c" size="small" v-if="scope.row.state === 0" >启用</span>
					<span style="color:  red" size="small" v-else-if="scope.row.state === -1">禁用</span>
					<span style="color: #cf9236" size="small" v-else>未知</span>
				</template>
			</el-table-column>
			<el-table-column prop="manager.username" label="管理员" width="180" sortable>
			</el-table-column>
			<el-table-column prop="parent.name" label="上级部门" width="180" sortable>
			</el-table-column>
			<el-table-column label="操作" >
				<template scope="scope">
					<el-button size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
					<el-button type="danger" size="small" @click="handleDel(scope.$index, scope.row)">删除</el-button>
				</template>
			</el-table-column>
		</el-table>

		<!--工具条-->
		<el-col :span="24" class="toolbar">
			<el-button type="danger" @click="batchRemove" :disabled="this.sels.length===0">批量删除</el-button>
			<!--<el-pagination layout="prev, pager, next" @current-change="getDepartments" :page-size="5" :total="total" :current-page="currentPage" style="float:right;">-->
			<!--</el-pagination>-->
			<el-pagination
					@current-change="handleCurrentChange"
					:current-page="currentPage"
					:page-size="pageSize"
					layout="prev, pager, next"
					:total="total"
					style="float:right;">
			</el-pagination>
		</el-col>

		<!--编辑界面
			:visible.sync 控制当前窗口是否显示
			:rules  表单校验规则
			ref  给当前表单引用一个别名
		-->
		<el-dialog :title="title" :visible.sync="departmentFormVisible" :close-on-click-modal="false">
			<el-form :model="departmentForm" label-width="80px" :rules="departmentFormRules" ref="departmentForm">

				<!-- prop="name" 申明表单属性 叫 name -->
				<el-form-item label="名称" prop="name">
					<el-input v-model="departmentForm.name" auto-complete="off"/>
				</el-form-item>
				<el-form-item label="编号" prop="sn">
					<el-input v-model="departmentForm.sn" auto-complete="off"/>
				</el-form-item>
				<el-form-item label="状态">
					<el-radio-group v-model="departmentForm.state">
						<el-radio class="radio" :label="0">启用</el-radio>
						<el-radio class="radio" :label="-1">禁用</el-radio>
					</el-radio-group>
				</el-form-item>
				<el-form-item label="管理员" >
					<!--<el-input v-model="departmentForm.manager" auto-complete="off"></el-input>-->
					<!--
					  	el-option  选择项
					  	item  遍历后得到的值
					  	:label 选择后展示在选择框中的内容
					  	:value 选择后要传给后端的值
					-->
					<el-select v-model="departmentForm.manager" value-key="id" clearable placeholder="请选择">
						<el-option
								v-for="item in employee"
								:key="item.id"
								:label="item.username"
								:value="item">
							<span style="float: left">{{ item.username }}</span>
							<span style="float: right; color: #8492a6; font-size: 13px">{{ item.phone }}</span>
						</el-option>
					</el-select>
				</el-form-item>
				<el-form-item label="上级部门">
					<!--<el-input v-model="departmentForm.parent" auto-complete="off"></el-input>-->
					<!--
						label:'name' 下拉列表展示的内容
						value:'id'  发送到后台的数据
						根据elementUI中 级联选择器 props的属性
						:options  需要遍历的数据
					-->
					<el-cascader v-model="departmentForm.parent"
								 :options="deptTree"
								 :props="{
							 checkStrictly: true,
							 label:'name',
							 value:'id'
							 }"
								 clearable/>
				</el-form-item>

			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click.native="departmentFormVisible = false">取消</el-button>
				<el-button type="primary" @click.native="departmentSubmit" :loading="departmentLoading">提交</el-button>
			</div>
		</el-dialog>
	</section>
</template>

<script>
	import util from '../../common/js/util'
	//import NProgress from 'nprogress'
	import { getDepartmentListPage, removeDepartment, batchRemoveDepartment, editDepartment, addDepartment } from '../../api/api';

	export default {
		data() {
			return {
				filters: {
					keyword: ''
				},
				departments: [],
				employee: [],
				deptTree: [],
                currentPage:1,
				pageSize:5,
                title:"",
				listLoading: false,
				sels: [],//列表选中行  所有选中对的行都会传进来

				departmentFormVisible: false,//编辑界面是否显示
				departmentLoading: false,
				departmentFormRules: {
					name: [
						{ required: true, message: '请输入姓名', trigger: 'blur' }
					],
					sn: [
						{ required: true, message: '请输入编号', trigger: 'blur' }
					]
				},
                //表单数据
				departmentForm: {
					id:null,
                    name: '',
					sn:'',
                    state: 0,
                    manager: null,
                    parent: null
				},
			}
		},
		methods: {
            findCurrent(){
                this.currentPage = 1;
                this.getEmployees();
            },
			handleCurrentChange(val) {
				this.currentPage = val;
				this.getDepartments();
			},
			//获取用户列表 分页展示
			getDepartments() {
               // alert(currentPage)
               //  if (currentPage){
               //      this.currentPage=currentPage
				// }
				let para = {
					currentPage: this.currentPage,
					keyword: this.filters.keyword, // 高级查询
					pageSize:this.pageSize
				};
				this.listLoading = true; // 开启忙等框
				this.$http.post("/dept",para)
					.then(result=>{
                        console.log(para)
					    console.log(result)
						result = result.data;
						this.departments = result.rows;
						 this.total = result.total; // 动态获取总条数
                        this.listLoading = false; // 关闭忙等框
					}).catch(result=>{
					    console.log(result);
					    alert("系统错误！");
				})
				//NProgress.start();
				// getDepartmentListPage(para).then((res) => {
				// 	this.total = res.data.total;
				// 	this.departments = res.data.departments;
				// 	this.listLoading = false;
				// 	//NProgress.done();
				// });
			},

			//删除
            handleDel: function (index, row) {
                this.$confirm('确认删除该记录吗?', '温馨提示', {
                    type: 'warning'
                }).then(() => {// 点击确定
                    this.listLoading = true;// 打开忙等框
                    //NProgress.start();
                    //let para = { id: row.id };
                    this.$http.delete("/dept/"+row.id).then(result=>{
                        //关闭加载效果
                        this.listLoading = false;// 关闭忙等框
                        result = result.data; // AjaxResult
                        //删除成功提示
                        if(result.success){
                            this.$message({
                                message: '删除成功！',
                                type: 'success'
                            });
                            this.page = 1;
                            //重新加载列表数据
                            this.getDepartments();
                        }else {
                            //删除失败提示
                            this.$message({
                                message: result.message,
                                type: 'error'
                            });
                            this.page = 1;
                            //重新加载列表数据
                            this.getDepartments();
                        }
                    }).catch(result=>{
                        //失败提示
                        this.$message({
                            message: result.message,
                            type: 'error'
                        });
                        this.page = 1;
                        //重新加载列表数据
                        this.getDepartments();
                    });
                }).catch(() => {

                });
            },

            //显示编辑界面
			handleEdit: function (index, row) {
                this.getDeptTree();
                this.title = "编辑"
				this.departmentFormVisible = true;
				this.departmentForm = Object.assign({}, row); // 克隆回显
                console.log(row)
                let dirPath = row.dirPath; //  数据格式 /72/73
                if(dirPath){ // 非空判断
					let str = dirPath.split("/");// ["","72","","73"]
					// 遍历字符串
					let parent = [];
					for(let i = 1; i<str.length-1;i++){
					    // 字符串转换为int
                        parent.push(parseInt(str[i]));
					}
					console.log(parent)
                    this.departmentForm.parent = parent;
                }
            },
			//显示新增界面
			handleAdd: function () {
                this.getDeptTree();
                this.title = "新增"
				this.departmentFormVisible = true;
				this.departmentForm = { // 清空
                    id:null,
                    name: '',
                    sn:'',
                    state: 0,
                    manager: null,
                    parent: null
				};
			},

			//编辑或者新增 提交表单
			departmentSubmit: function () {
			    // 主动开启表单校验
				this.$refs.departmentForm.validate((valid) => {
					if (valid) {// 校验通过
						this.$confirm('确认提交吗？', '提示', {}).then(() => { // 点击确认
							this.departmentLoading = true;
							//NProgress.start();
							let para = Object.assign({}, this.departmentForm);// 克隆一份表单数据
							console.log(para.parent)
							// 处理后台数据格式
							if(para.parent){ // 非空判断
							    let parent = para.parent;// id数组
							    // 拿到数组的最后一位
                                let pad = parent[parent.length-1]
								// 重新赋值给para
                                para.parent = {"id":pad};
							}
							this.$http.put("/dept",para)
								.then(result=>{
                                this.departmentLoading = false;// 关闭忙等
                                this.departmentFormVisible = false; // 关闭弹出
								result = result.data; // AjaxResult
                                if(result.success){
                                    this.$message({
                                        message: '操作成功！',
                                        type: 'success'
                                    });
                                }else {
                                    //操作失败提示
                                    this.$message({
                                        message: result.message,
                                        type: 'error'
                                    });
                                }
                                this.page = 1;
                                //重新加载列表数据
                                this.getDepartments();
                            }).catch(result=>{
                                this.departmentLoading = false;// 关闭忙等
                                this.$message({
                                    message: "操作失败",
                                    type: 'error'
                                });
							})
						});
					}
				});
			},

			selsChange: function (sels) { // 所以选中的对象都会传进来
				this.sels = sels;
				console.log(sels)
			},
			//批量删除
			batchRemove: function () {
				var ids = this.sels.map(item => item.id);
                this.$confirm('确认删除选中记录吗？', '提示', {
					type: 'warning'
				}).then(() => { // 点击确定
					this.listLoading = true; // 打开忙等框
					//NProgress.start();
					// let para = { ids: ids };

					// axios发送Ajax请求
					this.$http.patch("/dept",ids).then(result=>{
                        //关闭加载效果
                        this.listLoading = false;
                        result = result.data; // AjaxResult
                        //删除成功提示
                        if(result.success){
                            this.$message({
                                message: '删除成功！',
                                type: 'success'
                            });
                        }else {
                            //删除失败提示
                            this.$message({
                                message: result.message,
                                type: 'error'
                            });
                        }
                        this.page = 1;
                        //重新加载列表数据
                        this.getDepartments();
                    }).catch(result=>{ // 点击取消
                        //失败提示
                        this.$message({
                            message: result.message,
                            type: 'error'
                        });
                        this.page = 1;
                        //重新加载列表数据
                        this.getDepartments();
                    });
					// batchRemoveDepartment(para).then((res) => {
					// 	this.listLoading = false;
					// 	//NProgress.done();
					// 	this.$message({
					// 		message: '删除成功',
					// 		type: 'success'
					// 	});
					// 	this.getDepartments();
					// });
				}).catch(() => {

				});
			},

			// 获取员工列表 集合
			getEmployee (){
			    this.$http.get("/employee")
					.then(reslut=>{
					    reslut = reslut.data; // List<Employee>
						this.employee = reslut;
					})
			},
			// 获取上级部门树
			getDeptTree (){
			    this.$http.get("/dept/tree")
					.then(result=>{
					    console.log(result)
					    result = result.data;
					    this.deptTree = result;
					})
			}
		},
		mounted() {
			this.getDepartments();
			this.getEmployee();
		}
	}

</script>

<style scoped>

</style>